package com.ys168.gam.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.ys168.gam.bean.JobInfo;

/**
 * @author Jason Krebs
 * @since 2015年6月10日
 */
public class DownloadUtil {

    public static void download(JobInfo jobInfo, String savePath) throws Exception {
        HttpURLConnection conn = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        
        URL url = jobInfo.getUrl();

        int suffixIndex = url.toString().lastIndexOf(".");
        String suffixType = url.toString().substring(suffixIndex + 1);

        String name = jobInfo.getIndex() + "." + suffixType;

        try {
            conn = (HttpURLConnection) url.openConnection();
            int timeout = ConfigLoader.getDownloadTimeout();
            if (timeout > 0) {
                conn.setConnectTimeout(timeout);
            }
            if (conn.getResponseCode() != 200) {
                throw new Exception("Connection Error:" + conn.getResponseCode());
            }

            File file = new File(savePath + "/" + name);
            bis = new BufferedInputStream(conn.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(file));

            byte[] b = new byte[CACHE_SIZE];
            int len = 0;
            while ((len = bis.read(b)) != -1) {
                bos.write(b, 0, len);
            }
        }
        catch (Exception e) {
            throw e;
        }
        finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (bis != null) {
                    bis.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
            }
            catch (Exception e) {
                throw e;
            }
        }
    }

    private static final int CACHE_SIZE = 1024;
}
